import React, { useState, forwardRef, useCallback } from 'react';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { Input, InputNumber, Select, App, Button, Space, DatePicker } from 'antd';
import { MONEY_UNIT } from '@/config';
import dayjs from 'dayjs';
import styles from './index.module.scss';

/**
 * WhereSelledEditor
 * 输入：交易地址、交易价格、交易时间
 * 展示：3列列表，可添加多条
 * value: [{ plat: url, price, date }]
 * onChange: (nextList) => void
 */
export default forwardRef(({ value = [], onChange }, ref) => {
  const initState = () => ({
    addr: '',
    price: '',
    currency: '1',
    date: '',
    visible: false,
  });
  const [state, setState] = useState(initState);
  const { message } = App.useApp();

  const list = Array.isArray(value)
    ? value.filter(Boolean).map(i => (typeof i === 'string' ? { plat: i } : i))
    : [];

  const formatPrice = (item={}) => {
    const raw = item?.price;
    if (raw === undefined || raw === null || raw === '') return '--';
    const s = String(raw).trim();
    const m = s.match(/^([^:]+):\s*(.+)$/);
    if (m) {
      const amount = m[1].trim();
      const code = m[2].trim();
      const unitLabel = MONEY_UNIT?.[code] || '';
      return unitLabel ? `${amount}${unitLabel}` : amount;
    }
    return s;
  };

  // 从URL中获取域名
  const getDomain = useCallback((raw='') => {
    if (!raw || typeof raw !== 'string') return '';
    const s = raw.trim();
    const match = s.match(/^(?:https?:\/\/)?([^\/?#:]+)(?:[\/?#:]|$)/i);
    return match ? match[1] : '';
  }, []);

  const normalizeUrl = useCallback((raw='') => {
    if (!raw) return '';
    const trimmed = raw.trim();
    if (!/^https?:\/\//i.test(trimmed)) {
      return `https://${trimmed}`;
    }
    return trimmed;
  }, []);

  // 判断是否为有效的链接地址（宽松判断）
  const isUrl = useCallback((str='') => {
    if (typeof str !== 'string') return false;
    const trimmed = str.trim();
    if (!trimmed) return false;

    let urlToTest = trimmed;
    if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) urlToTest = 'http://' + trimmed;

    try {
      const url = new URL(urlToTest);
      if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
      const host = url.hostname;
      if (!host) return false;

      // 👇 关键改进：要求 hostname 至少包含一个点（排除 'aaaa', 'localhost' 等）
      if (!host.includes('.')) return false;

      return true;
    } catch {
      return false;
    }
  }, []);

  const updateValue = (next=[]) => onChange?.(next);

  const clearInputs = () => setState(initState);

  const showEditor = () => setState(o => ({ ...o, visible: true }));
  const hideEditor = () => setState(initState);

  const handleAdd = () => {
    message.destroy();
    const addr = (state.addr || '').trim();
    if (!addr) return message.warning('请输入交易地址');
    // 保存原始地址文本（不强制添加协议）
    const platValue = addr;
    if (state.price === undefined || state.price === null || state.price === '') return message.warning('请输入交易价格');
    if (!state.date) return message.warning('请选择交易年份');

    // 保存为 “金额:币种编码”（仅使用英文冒号）
    const priceStr = `${state.price}:${state.currency}`;
    const next = [...list, { plat: platValue, price: priceStr, date: state.date?.trim() || '' }];
    updateValue(next);
    clearInputs();
  };

  const handleRemove = (index) => {
    const next = list.filter((_, i) => i !== index);
    updateValue(next);
  };

  const currencyOptions = Object.entries(MONEY_UNIT || {}).map(([value, label]) => ({ value, label }));

  return (
    <div className={styles['container']}>
      {/* 已添加列表（3列展示） */}
      <div className={styles['grid']}>
        {
          list.map((item, index) => {
            const linkable = isUrl(item.plat || '');
            const href = linkable ? normalizeUrl(item.plat || '') : '';
            const domain = linkable ? getDomain(href) : '';
            return (
              <div key={index} className={styles['item']}>
                <div style={{ width: '44%' }}>
                  {
                    linkable ?
                      <a href={href} target="_blank" rel="noreferrer">{domain || href}</a>
                      :
                      <span>{item.plat||''}</span>
                  }
                </div>
                <div style={{ width: '30%',wordBreak:'break-all',paddingRight:2 }}>{formatPrice(item)}</div>
                <div style={{ width: '26%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>{item.date || '--'} 年</span>
                  <Button danger type="text" size="small" icon={<DeleteOutlined />} onClick={() => handleRemove(index)} />
                </div>
              </div>
            );
          })
        }
      </div>

      {/* 编辑行（点击添加后才显示） */}
      {state.visible ? (
        <div className={styles['editRow']}>
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            <Space.Compact size="small" style={{ width: '100%' }}>
              <Input
                className={styles['input']}
                size="small"
                style={{ flex: 2, minWidth: 0 }}
                placeholder="交易地址"
                value={state.addr}
                onChange={e => setState(o => ({ ...o, addr: e.target.value }))}
              />
              <InputNumber
                className={styles['input']}
                size="small"
                style={{ flex: 1, minWidth: 0 }}
                placeholder="金额"
                controls={false}
                step={0.01}
                min={0}
                stringMode
                value={state.price}
                onChange={v => setState(o => ({ ...o, price: v }))}
              />
              <Select
                style={{width:60}}
                popupMatchSelectWidth={false}
                size="small"
                placeholder="币种"
                options={currencyOptions}
                value={state.currency}
                onChange={v => setState(o => ({ ...o, currency: v }))}
              />
              <DatePicker
                size="small"
                picker="year"
                style={{ flex: 1, minWidth: 0 }}
                placeholder="年份"
                disabledDate={(current) => current && current.year() > dayjs().year()}
                value={state.date ? dayjs(state.date, 'YYYY') : null}
                onChange={(v) => setState(o => ({ ...o, date: v ? v.format('YYYY') : '' }))}
              />
            </Space.Compact>
            <Space size="small">
              <Button
                type="primary"
                size="small"
                onClick={handleAdd}
                disabled={!state.addr?.trim() || (state.price === null || state.price === undefined || state.price === '') || !state.date}
              >
                确定
              </Button>
              <Button size="small" onClick={hideEditor}>取消</Button>
            </Space>
          </Space>
        </div>
      ) : (
        <div className={styles['editRow']}>
          <Button size="small" type="dashed" icon={<PlusOutlined />} onClick={showEditor}>
            添加交易记录
          </Button>
        </div>
      )}
    </div>
  );
});